import CryptoJS from 'crypto-js'

/**
 * base64 转 Unit8Array
 * @param bs64Data
 * @returns Unit8Array
 */
export function base64toUnit8Array(bs64Data: string): Uint8Array {
  let base64Str = dncBase64(bs64Data)
  return convertWordArrayToUint8Array(base64Str)
}

/**
 * 字符串转base64
 * @param str
 * @returns
 */
function base64(str: string) {
  return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(str))
}

/**
 * 解析base 64
 * @param bStr
 * @returns {*}
 */
function dncBase64(bStr: string) {
  return CryptoJS.enc.Base64.parse(bStr)
}

/**
 * wordArray 转 Unit8Array
 * @param wordArray 这里的 WordArray 是 CryptoJS 的一个核心类，具体是啥完全不知道
 * @returns Unit8Array
 */
function convertWordArrayToUint8Array(wordArray: CryptoJS.lib.WordArray): Uint8Array {
  let len = wordArray.words.length,
    u8_array = new Uint8Array(len << 2),
    offset = 0,
    word,
    i

  for (i = 0; i < len; i++) {
    word = wordArray.words[i]
    u8_array[offset++] = word >> 24
    u8_array[offset++] = (word >> 16) & 0xff
    u8_array[offset++] = (word >> 8) & 0xff
    u8_array[offset++] = word & 0xff
  }
  return u8_array
}
